package com.leetcode.design;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Dennis Li
 * @date 2020/10/28 21:12
 */
public class Twitter2 {

    private long serial = Long.MIN_VALUE;

    static class User {

        int userId;

        Map<Integer, User> followers;
        Map<Integer, User> followees;

        Tweet head, tail;

        public User(int userId) {
            this.userId = userId;
            this.followers = new HashMap<>();
            this.followees = new HashMap<>();
            head = new Tweet(userId, -1, 0);
            tail = new Tweet(userId, -1, 0);
            head.next = tail;
            tail.prev = head;
        }
    }

    static class Tweet {
        int userId, tweetId;

        long time;

        Tweet next, prev;

        public Tweet(int userId, int tweetId, long time) {
            this.userId = userId;
            this.tweetId = tweetId;
            this.time = time;
        }
    }

    private static long timer = 0L;

    private Map<Integer, User> users;

    /**
     * Initialize your data structure here.
     */
    public Twitter2() {
        users = new HashMap<>();
    }

    /**
     * Compose a new tweet.
     */
    public void postTweet(int userId, int tweetId) {
        User user = getUser(userId);
        Tweet tweet = new Tweet(userId, tweetId, timer++);
        postNewTweet(user, tweet);
    }

    /**
     * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
     */
    public List<Integer> getNewsFeed(int userId) {
        User user = getUser(userId);
        Queue<Tweet> queue = new PriorityQueue<>(Comparator.comparingLong(o -> o.time));

        Map<Integer, Tweet> followeeTweets = new HashMap<>();
        user.followees.forEach((id, followee) -> {
            if (followee.tail.prev != followee.head) {
                followeeTweets.put(id, followee.tail.prev);
            }
        });

        Set<Integer> exclude = new HashSet<>();

        while (followeeTweets.size() > exclude.size()) {
            for (int id : followeeTweets.keySet()) {
                if (exclude.contains(id)) {
                    continue;
                }
                Tweet tweet = followeeTweets.get(id);
                if (tweet.prev.tweetId == -1) {
                    exclude.add(id);
                } else {
                    followeeTweets.put(id, tweet.prev);
                }
                if (queue.size() < 10) {
                    queue.offer(tweet);
                } else {
                    Tweet peek = queue.peek();
                    if (tweet.time > peek.time) {
                        Tweet poll = queue.poll();
                        exclude.add(poll.userId);
                        queue.offer(tweet);
                    } else {
                        exclude.add(tweet.userId);
                    }
                }
            }
        }

        LinkedList<Integer> list = new LinkedList<>();
        while (!queue.isEmpty()) {
            list.offerFirst(queue.poll().tweetId);
        }
        return list;
    }

    /**
     * Follower follows a followee. If the operation is invalid, it should be a no-op.
     */
    public void follow(int followerId, int followeeId) {
        // 自己关注自己是非法的
        if (followeeId == followerId) {
            return;
        }
        User follower = getUser(followerId);
        User followee = getUser(followeeId);

        followee.followers.put(followerId, follower);
        follower.followees.put(followeeId, followee);
    }

    public void unfollow(int followerId, int followeeId) {
        // 自己取消关注自己是非法的
        if (followeeId == followerId) {
            return;
        }
        User follower = getUser(followerId);
        User followee = getUser(followeeId);

        followee.followers.remove(followerId);
        follower.followees.remove(followeeId);
    }

    private void postNewTweet(User user, Tweet tweet) {
        Tweet prev = user.tail.prev;
        user.tail.prev = tweet;
        prev.next = tweet;
        tweet.next = user.tail;
        tweet.prev = prev;
    }

    private User getUser(int userId) {
        if (!users.containsKey(userId)) {
            users.put(userId, new User(userId));
            // 将自己加入关注者
            User user = users.get(userId);
            user.followees.put(userId, user);
        }
        return users.get(userId);
    }

    public static void main(String[] args) {
        Twitter2 twitter = new Twitter2();
        // 用户1发送了一条新推文 (用户id = 1, 推文id = 5).
        twitter.postTweet(1, 5);

// 用户1的获取推文应当返回一个列表，其中包含一个id为5的推文.
        twitter.getNewsFeed(1);

// 用户1关注了用户2.
        twitter.follow(1, 2);

// 用户2发送了一个新推文 (推文id = 6).
        twitter.postTweet(2, 6);

// 用户1的获取推文应当返回一个列表，其中包含两个推文，id分别为 -> [6, 5].
// 推文id6应当在推文id5之前，因为它是在5之后发送的.
        twitter.getNewsFeed(1);

// 用户1取消关注了用户2.
        twitter.unfollow(1, 2);

// 用户1的获取推文应当返回一个列表，其中包含一个id为5的推文.
// 因为用户1已经不再关注用户2.
        twitter.getNewsFeed(1);
    }

}
